package com.ipay.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ipay.redis.JedisConnectionPool;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.ipay.common.Base64Coder;
import com.ipay.entity.BankInfoEntity;
import com.ipay.service.ApiPayService;
import com.ipay.service.BankInfoService;
import com.ipay.service.TradeRecordService;
import com.ipay.utils.Constant;
import com.ipay.utils.MD5;
import com.ipay.utils.MapUtils;
import com.ipay.utils.PageUtils;
import com.ipay.utils.Query;
import com.ipay.utils.R;

/**
 * 支付渠道商管理
 * 
 * @author Luohx
 */
@Transactional
@Controller
@RequestMapping("/bankInfo")
public class BankInfoController extends AbstractController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private BankInfoService bankInfoService;
	@Autowired
	private ApiPayService apiPayService;
	@Autowired
	private TradeRecordService tradeRecordService;

	@Autowired
	private JedisConnectionPool pool;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@ResponseBody
	@RequiresPermissions("bankInfo:list")
	public R list(@RequestParam Map<String, Object> params) {
		logger.info("params==" + params.toString());
		// 查询列表数据
		Query query = new Query(params);
		logger.info("query==" + query.toString());

		List<BankInfoEntity> payChannelList = bankInfoService.queryList(query);
		int total = bankInfoService.queryTotal(query);
		logger.info("total==" + total);

		PageUtils pageUtil = new PageUtils(payChannelList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 信息
	 * @throws IOException 
	 */
	@RequestMapping("/info/{id}")
	@ResponseBody
	@RequiresPermissions("bankInfo:info")
	public R info(@PathVariable("id") String id,HttpServletRequest request, HttpServletResponse response) throws IOException {
		BankInfoEntity bankInfo = bankInfoService.queryObject(id);
		return R.ok().put("bankInfo", bankInfo);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@ResponseBody
	@RequiresPermissions("bankInfo:save")
	public R save(@RequestBody BankInfoEntity bankInfo) {
		//根据商户号、状态查询是否已有启用的银行卡 没有默认启用、有的话就禁用
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("merchantNo", bankInfo.getMerchantNo());
		map.put("payState", Constant.Status.ENABLE.getValue());
		BankInfoEntity bank = bankInfoService.queryInfoByParams(map);
		if(bank != null){
			bankInfo.setPayState(Constant.Status.DISABLE.getValue());
		}else{
			bankInfo.setPayState(Constant.Status.ENABLE.getValue());
		}
		//根据商户号查询商户表
		bankInfoService.save(bankInfo);
		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@ResponseBody
	@RequiresPermissions("bankInfo:update")
	public R update(@RequestBody BankInfoEntity bankInfo) {
		//根据商户号、状态查询是否已有启用的银行卡 没有默认启用、有的话就禁用
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("merchantNo", bankInfo.getMerchantNo());
		map.put("payState", Constant.Status.ENABLE.getValue());
		BankInfoEntity bank = bankInfoService.queryInfoByParams(map);
		if(bank != null){
			//判断修改状态和查询记录状态是否一致
			if(bank.getPayState().intValue() == Constant.Status.ENABLE.getValue()
					&& bankInfo.getId().longValue() != bank.getId().longValue()){
				return R.error("只能开启一个银行卡");
			}else{
				//查询商户当天是否有交易流水，如果有不能启用禁用、如果没有可以启用禁用
				//今日交易金额
				Map<String, Object> mapDatetrade = new HashMap<>();
				mapDatetrade.put("busId", bankInfo.getMerchantNo());
				BigDecimal todaySumAmount = tradeRecordService.findTodaySumAmountByBusId(mapDatetrade);
				if (todaySumAmount == null || todaySumAmount.compareTo(new BigDecimal(0)) != 1) { //结果是:-1 小于,0 等于,1 大于
					if(bankInfoService.update(bankInfo) > 0){
						return R.ok("修改成功");
					}
				}else{
					return R.error("商户当日银行卡有交易金额，无法启用禁用");
				}
			}
		}else{
			if(bankInfoService.update(bankInfo) > 0){
				return R.ok("修改成功");
			}
		}
		return R.error("修改失败");
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	@RequiresPermissions("bankInfo:delete")
	public R delete(@RequestBody String[] ids) {
		bankInfoService.deleteBatch(ids);
		return R.ok();
	}
	
	/**
	 *银行信息列表
	 */
	@RequestMapping("/getBankInfoSelect")
	@ResponseBody
	@RequiresPermissions("bankInfo:list")
	public R getBankInfoSelect(@RequestBody String merchantNo,HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<String, Object>();
		/*String userType = getUser().getUserType();
		if(userType != null && userType.equals(Constant.USER_TYPE_SH)){
			String merchantNo = getUser().getMerchantNo();
		}*/
		params.put("merchantNo", merchantNo);
		logger.info("params==" + params.toString());
		// 查询列表数据
		//String options = bankInfoService.getBankInfoSelect(params);
		List<BankInfoEntity> list = bankInfoService.getBankInfoSelect(params);
		logger.info("options==" + list);

		return R.ok().put("options", list);
	}


	/**
	 * 测试方法
	 * 	https://www.***.cn/pay-manager/bankInfo/payView
	 */
	@RequestMapping(value = "/payView", method = RequestMethod.GET)
	public ModelAndView payView() throws Exception {
		String merchantNo="D2017103111000000011";
		String codeNo="20171031205938";
		String mchPayKey="c45f4006f96776b53ed13e341eb49306";
		String sponsorOrderNo = "D2017111611000000332";
		logger.info("===付款订单号====sponsorOrderNo:"+sponsorOrderNo);
		String notifyUrl = "https://www.***.cn/pay-manager/bankInfo/doCallbackNotify";
		Map<String,String> map=new HashMap<String,String>();
		map.put("merchantNo",merchantNo);//商户编号
		map.put("codeNo",codeNo);//收款员编号
		map.put("sponsorOrderNo", sponsorOrderNo);//付款订单号
		map.put("payMoney","0.01");//付款金额
		map.put("callbackUrl","https://www.***.cn/wechat/auth/isMerchant");//前台通知地址
		map.put("notifyUrl",notifyUrl);//回调地址（订单状态）
		String payremark = URLEncoder.encode("国外旅泰国旅游保险","utf-8");///订单说明
		map.put("payremark",payremark);

		System.out.println("wxJsPay====:"+ JSON.toJSONString(map));
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		//TODO 查询商户相关数据
		String parameter= Base64Coder.encode(strtosign);
		String signstr = MD5.sign(parameter, "&payKey=" + mchPayKey, "utf-8");
		System.out.println("==========signstr===========:"+signstr);
		map.put("sign", signstr);
		String param = strtosign + "&sign=" + signstr;
		System.out.println("==========param===========:"+param);
		String redirectUrl =pool.getBaseUrl() + "/auth/payView?" + param;
		return new ModelAndView("redirect:"+redirectUrl);
	}
	/**
	 * 测试方法
	 * https://www.***.cn/wechat/auth/pay?merchantNo=D2017103111000000011&codeNo=20171031205938
	 */
	@RequestMapping(value = "/auth/pay", method = RequestMethod.GET)
	public void pay() throws Exception {
		String merchantNo="D2017103111000000011";
		String codeNo="20171031205938";
		String mchPayKey="c45f4006f96776b53ed13e341eb49306";
		String sponsorOrderNo = "D2017111611000000332";
		logger.info("===付款订单号====sponsorOrderNo:"+sponsorOrderNo);
		String notifyUrl = "https://www.***.cn/pay-manager/bankInfo/doCallbackNotify";
		Map<String,String> map=new HashMap<String,String>();
		map.put("merchantNo",merchantNo);//商户编号
		map.put("codeNo",codeNo);//收款员编号
		map.put("sponsorOrderNo", sponsorOrderNo);//付款订单号
		map.put("payMoney","0.01");//付款金额
		map.put("callback_url","https://www.***.cn/wechat/auth/isMerchant");//前台通知地址
		map.put("notifyUrl",notifyUrl);//回调地址（订单状态）
		String payremark = URLEncoder.encode("国外旅泰国旅游保险","utf-8");///订单说明
		map.put("payremark",payremark);
		apiPayService.dsfNotifyUrl(map,mchPayKey,"https://www.***.cn/wechat/auth/pay");
	}


	/**
	 * 测试第三方回调
	 * 道盈 聚合支付  平台来的通知处理
	 * /bankInfo/doCallbackNotify
	 */
	@RequestMapping(value = "/doCallbackNotify", method = RequestMethod.POST)
	public void doCallbackNotify(HttpServletRequest request) throws Exception {
		String mchPayKey="c45f4006f96776b53ed13e341eb49306";
        /*
        mapdsfbak.put("status",order.getStatus());//1已支付
        mapdsfbak.put("sponsorOrderNo",order.getSponsorOrderNo());//发起方订单号
        mapdsfbak.put("resource",order.getResource());//来源（0 微信、1 支付宝）
        mapdsfbak.put("amount", String.valueOf(total_fee));//金额
        mapdsfbak.put("recordNo", order.getRecordno());//商户订单号
        mapdsfbak.put("time_end", order.getTimeEnd());//
        mapdsfbak.put("bank_type", order.getBankType());//
        mapdsfbak.put("openid", order.getOpenid());
        */
		String status = request.getParameter("status");//1已支付
		String sponsorOrderNo = request.getParameter("sponsorOrderNo");//发起方订单号
		String resource = request.getParameter("resource");//来源（0 微信、1 支付宝）
		String amount = request.getParameter("amount");////金额
		String recordNo = request.getParameter("recordNo");//商户订单号
		String time_end = request.getParameter("time_end");//1已支付
		String bank_type = request.getParameter("bank_type");//1已支付
		String openid = request.getParameter("openid");//1已支付
		String sign = request.getParameter("sign");//签名
		Map<String,String> mapdsfbak=new HashMap<>();
		mapdsfbak.put("status",status);//1已支付
		mapdsfbak.put("sponsorOrderNo",sponsorOrderNo);//发起方订单号
		mapdsfbak.put("resource",resource);//来源（0 微信、1 支付宝）
		mapdsfbak.put("amount", amount);//金额
		mapdsfbak.put("recordNo", recordNo);//商户订单号
		mapdsfbak.put("time_end", time_end);//
		mapdsfbak.put("bank_type", bank_type);//
		mapdsfbak.put("openid", openid);
		String strtosign = MapUtils.formatUrlMap(mapdsfbak, false, false);
		System.out.println("****************strtosign***********************:"+strtosign);
		//TODO 查询商户相关数据  =payKey
		String parameter= Base64Coder.encode(strtosign);
		String signstr = MD5.sign(parameter, "&payKey="+mchPayKey , "utf-8");
		System.out.println("****************signstr***********************:"+signstr);
		if(!signstr.equals(sign)){
			logger.info("签名错误");
		}
	}
}
